<?php

namespace app\admin\utils;

use think\facade\Cache;

/**
 * 后台登录
 */
class User
{
    /**
     * 登录用户
     * @return string
     */
    public static function getUid()
    {
        $token = self::getToken();

        $admin_token="admin_uid_".$token;

        return model("AdminToken")->where(['access_token'=>$admin_token])->value('uid');

    }

    public static function getToken()
    {
        return request()->header('X-Token') ? request()->header('X-Token') : request()->param('X-Token');
    }

    public static function removeToken()
    {
        $token = self::getToken();
        $admin_token="admin_uid_".$token;
        return model("AdminToken")->where(['access_token'=>$admin_token])->delete();
    }

    public static function login($username, $password)
    {
        $result = model('Admin')->checkPassword($username, $password,0);
        if ($result) {
            // 更新登录信息
            model('Admin')->login($result['uid']);

            $token = uniqid();

            $admin_token="admin_uid_".$token;

            model("AdminToken")->where(['uid'=>$result['uid']])->delete();

            $expire=time()+3600*24*3;
            model("AdminToken")->insert(['access_token'=>$admin_token,'uid'=>$result['uid'],'create_time'=>time(),'expire_time'=>$expire]);
            return $token;
        }
        return $result;
    }
}
